<template>
  <view class="container">
    <!-- 顶部操作栏 -->
    <view class="header-section">
      <view class="header-info">
        <text class="header-title">预约管理</text>
        <text class="header-subtitle">管理可预约时段和查看预约记录</text>
      </view>
      <view class="header-actions">
        <button class="time-slot-btn" @click="goToTimeSlotSetting">时段设置</button>
        <button class="refresh-btn" @click="fetchBookingList">刷新</button>
      </view>
    </view>

    <!-- 统计卡片 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-card">
          <view class="stat-icon total-icon">
            <text class="icon-text">📊</text>
          </view>
          <view class="stat-content">
            <text class="stat-number">{{ stats.totalBookings }}</text>
            <text class="stat-label">总预约</text>
          </view>
        </view>
        <view class="stat-card">
          <view class="stat-icon today-icon">
            <text class="icon-text">📅</text>
          </view>
          <view class="stat-content">
            <text class="stat-number">{{ stats.todayBookings }}</text>
            <text class="stat-label">今日预约</text>
          </view>
        </view>
        <view class="stat-card">
          <view class="stat-icon available-icon">
            <text class="icon-text">⏰</text>
          </view>
          <view class="stat-content">
            <text class="stat-number">{{ timeSlots.filter(s => s.status === 'available').length }}</text>
            <text class="stat-label">可用时段</text>
          </view>
        </view>
        <view class="stat-card">
          <view class="stat-icon booked-icon">
            <text class="icon-text">✅</text>
          </view>
          <view class="stat-content">
            <text class="stat-number">{{ timeSlots.filter(s => s.status === 'booked').length }}</text>
            <text class="stat-label">已预约</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 筛选器 -->
    <view class="filter-section">
      <view class="filter-tabs">
        <view
            class="filter-tab active"
        >
          <text class="tab-text">全部预约</text>
        </view>
      </view>
    </view>

    <!-- 预约列表 -->
    <view class="booking-list">
      <view class="list-header">
        <text class="list-title">预约记录</text>
        <text class="list-count">共 {{ bookingList.length }} 条</text>
      </view>

      <view v-if="!loading && bookingList && bookingList.length > 0">
        <view class="booking-item" v-for="booking in bookingList" :key="booking.id">
          <view class="booking-header">
            <view class="student-info">
              <image class="student-avatar" :src="booking.studentAvatar || '/static/default-avatar.png'"
                     mode="aspectFill"></image>
              <view class="student-details">
                <text class="student-name">{{ booking.studentName || '未知学生' }}</text>
                <text class="student-id">学生ID: {{ booking.studentId }}</text>
              </view>
            </view>
          </view>

          <view class="booking-content">
            <view class="booking-details">
              <view class="detail-row">
                <text class="detail-label">预约时间</text>
                <text class="detail-value">{{ formatAppointmentDate(booking.appointmentDate) }}</text>
              </view>
              <view class="detail-row">
                <text class="detail-label">申请时间</text>
                <text class="detail-value">{{ formatDateTime(booking.createTime) }}</text>
              </view>
              <view class="detail-row" v-if="booking.timeSlotId">
                <text class="detail-label">时段ID</text>
                <text class="detail-value">{{ booking.timeSlotId }}</text>
              </view>
              <view class="detail-row" v-if="booking.cancelReason">
                <text class="detail-label">取消原因</text>
                <text class="detail-value remark">{{ booking.cancelReason }}</text>
              </view>
              <view class="detail-row" v-if="booking.adminNotes">
                <text class="detail-label">管理员备注</text>
                <text class="detail-value remark">{{ booking.adminNotes }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-else-if="loading" class="loading-state">
        <view class="loading-icon">⏳</view>
        <text class="loading-text">加载中...</text>
      </view>

      <!-- 空状态 -->
      <view v-else class="empty-state">
        <view class="empty-icon">📝</view>
        <text class="empty-title">暂无预约</text>
        <text class="empty-desc">当前筛选条件下没有预约数据</text>
      </view>
    </view>
  </view>
</template>

<script>
import {API_CONFIG, getApiUrl, getRequestConfig, apiRequest} from '@/config/api.js'

export default {
  data() {
    return {
      loading: false,
      stats: {
        totalBookings: 0,
        todayBookings: 0
      },
      bookingList: [],
      timeSlots: []
    }
  },
  computed: {
    filteredBookings() {
      return this.bookingList
    }
  },
  created() {
    this.fetchBookingList()
  },

  methods: {
    async fetchBookingList() {
      this.loading = true
      try {
        console.log('=== 开始获取预约记录 ===');
        console.log('请求URL:', getApiUrl(API_CONFIG.ENDPOINTS.APPOINTMENT));
        
        const res = await apiRequest({
          url: getApiUrl(API_CONFIG.ENDPOINTS.APPOINTMENT),
          method: 'GET'
        })
        
        console.log('=== API完整响应 ===');
        console.log('响应对象:', JSON.stringify(res, null, 2));
        console.log('响应类型:', typeof res);
        console.log('响应code:', res?.code);
        console.log('响应message:', res?.message);
        console.log('响应data:', res?.data);
        console.log('data类型:', typeof res?.data);
        console.log('data是否为数组:', Array.isArray(res?.data));
        
        if (res?.data && Array.isArray(res.data)) {
          console.log('data长度:', res.data.length);
          if (res.data.length > 0) {
            console.log('第一条数据:', JSON.stringify(res.data[0], null, 2));
            console.log('第一条数据的字段:', Object.keys(res.data[0]));
          }
        }

        // 修复响应码判断，后端可能返回code=0或code=200
        if (res && (res.code === 200 || res.code === 0) && Array.isArray(res.data)) {
          console.log('✅ 数据格式正确，开始处理');
          this.bookingList = res.data
          console.log('设置bookingList长度:', this.bookingList.length);
          this.calculateStats()
        } else {
          console.log('❌ 响应格式不正确或无数据');
          console.log('条件检查:');
          console.log('- res存在:', !!res);
          console.log('- code正确:', res && (res.code === 200 || res.code === 0));
          console.log('- data是数组:', res && Array.isArray(res.data));
          
          this.bookingList = []
          this.stats = {totalBookings: 0, todayBookings: 0}
          
          // 如果有错误信息，显示具体错误
          if (res && res.message) {
            uni.showToast({title: res.message, icon: 'none'})
          } else {
            uni.showToast({title: '获取预约记录失败：数据格式错误', icon: 'none'})
          }
        }
      } catch (e) {
        console.error('❌ 获取预约记录异常:', e);
        console.error('错误详情:', e.message);
        this.bookingList = []
        this.stats = {totalBookings: 0, todayBookings: 0}
        uni.showToast({title: `获取预约记录失败: ${e.message}`, icon: 'none'})
      }
      this.loading = false
    },
    calculateStats() {
      console.log('开始计算统计数据，预约数量:', this.bookingList.length);
      this.stats.totalBookings = this.bookingList.length
      
      // 获取今天的日期字符串，格式: 2025-08-13
      const today = new Date().toISOString().split('T')[0]
      
      this.stats.todayBookings = this.bookingList.filter(booking => {
        return booking.appointmentDate === today
      }).length
      
      console.log('统计完成 - 总预约:', this.stats.totalBookings, '今日预约:', this.stats.todayBookings);
    },
    formatDateTime(dateInput) {
      // 改进时间格式化函数，处理不同的时间字段
      let date = null
      
      if (!dateInput) return '未知时间'
      
      // 如果是时间段对象
      if (typeof dateInput === 'object' && dateInput.date) {
        const dateStr = dateInput.date
        const startTime = dateInput.startTime || '00:00'
        const endTime = dateInput.endTime || '00:00'
        return `${dateStr} ${startTime}-${endTime}`
      }
      
      // 如果是日期字符串或Date对象
      try {
        date = new Date(dateInput)
        if (isNaN(date.getTime())) {
          return '时间格式错误'
        }
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
      } catch (e) {
        console.error('时间格式化错误:', e, dateInput)
        return '时间格式错误'
      }
    },
    formatAppointmentDate(dateInput) {
      if (!dateInput) return '未知日期'
      try {
        const date = new Date(dateInput)
        if (isNaN(date.getTime())) {
          return '日期格式错误'
        }
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
      } catch (e) {
        console.error('日期格式化错误:', e, dateInput)
        return '日期格式错误'
      }
    },
    goToTimeSlotSetting() {
      uni.navigateTo({
        url: '/pages/admin/time-slot-setting'
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background: #0B0F1A;
  padding: 40rpx;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;

  .header-info {
    .header-title {
      display: block;
      font-size: 48rpx;
      color: #FFFFFF;
      font-weight: bold;
      margin-bottom: 8rpx;
    }

    .header-subtitle {
      font-size: 28rpx;
      color: #AAB4BE;
    }
  }

  .header-actions {
    display: flex;
    gap: 16rpx;

    .time-slot-btn, .refresh-btn {
      background: #1a1f2e;
      border: 1rpx solid #2a2f3e;
      color: #FFFFFF;
      font-size: 26rpx;
      padding: 12rpx 20rpx;
      border-radius: 12rpx;
      transition: all 0.3s;

      &:active {
        background: #2a2f3e;
      }
    }

    .time-slot-btn {
      background: linear-gradient(135deg, #1976D2 0%, #2196F3 100%);
      box-shadow: 0 4rpx 16rpx rgba(25, 118, 210, 0.3);
    }
  }
}

.stats-section {
  margin-bottom: 40rpx;

  .stats-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20rpx;
  }

  .stat-card {
    background: #1a1f2e;
    border: 1rpx solid #2a2f3e;
    border-radius: 16rpx;
    padding: 30rpx;
    display: flex;
    align-items: center;
    box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-4rpx);
      box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
    }

    .stat-icon {
      width: 80rpx;
      height: 80rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;

      .icon-text {
        font-size: 36rpx;
      }

      &.total-icon {
        background: linear-gradient(135deg, #9C27B0 0%, #BA68C8 100%);
      }

      &.today-icon {
        background: linear-gradient(135deg, #2196F3 0%, #42A5F5 100%);
      }

      &.available-icon {
        background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
      }

      &.booked-icon {
        background: linear-gradient(135deg, #FF9800 0%, #FFB74D 100%);
      }
    }

    .stat-content {
      .stat-number {
        display: block;
        font-size: 36rpx;
        color: #FFFFFF;
        font-weight: bold;
        margin-bottom: 4rpx;
      }

      .stat-label {
        font-size: 24rpx;
        color: #AAB4BE;
      }
    }
  }
}

.filter-section {
  margin-bottom: 40rpx;

  .filter-tabs {
    display: flex;
    background: #1a1f2e;
    border: 1rpx solid #2a2f3e;
    border-radius: 12rpx;
    padding: 8rpx;
  }

  .filter-tab {
    flex: 1;
    text-align: center;
    padding: 16rpx;
    border-radius: 8rpx;
    transition: all 0.3s;

    .tab-text {
      font-size: 28rpx;
      color: #AAB4BE;
    }

    &.active {
      background: #1976D2;

      .tab-text {
        color: #FFFFFF;
        font-weight: 500;
      }
    }
  }
}

.booking-list {
  .list-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .list-title {
      font-size: 32rpx;
      color: #FFFFFF;
      font-weight: 500;
    }

    .list-count {
      font-size: 26rpx;
      color: #AAB4BE;
    }
  }
}

.booking-item {
  background: #1a1f2e;
  border: 1rpx solid #2a2f3e;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.3);
  }

  .booking-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;

    .student-info {
      display: flex;
      align-items: center;

      .student-avatar {
        width: 60rpx;
        height: 60rpx;
        border-radius: 50%;
        margin-right: 16rpx;
      }

      .student-details {
        .student-name {
          display: block;
          font-size: 28rpx;
          color: #FFFFFF;
          font-weight: 500;
          margin-bottom: 4rpx;
        }

        .student-id {
          font-size: 24rpx;
          color: #AAB4BE;
        }
        }
      }
    }

    .booking-content {
      margin-bottom: 20rpx;

      .booking-details {
        .detail-row {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12rpx;

          .detail-label {
            font-size: 26rpx;
            color: #AAB4BE;
          }

          .detail-value {
            font-size: 26rpx;
            color: #FFFFFF;

            &.remark {
              color: #AAB4BE;
              font-style: italic;
          }
        }
      }
    }
  }
}

.loading-state, .empty-state {
  text-align: center;
  padding: 100rpx 0;

  .loading-icon, .empty-icon {
    font-size: 80rpx;
    margin-bottom: 20rpx;
  }

  .loading-text, .empty-title {
    display: block;
    font-size: 32rpx;
    color: #FFFFFF;
    margin-bottom: 12rpx;
  }

  .empty-desc {
    font-size: 26rpx;
    color: #AAB4BE;
  }
}
</style>
